<template>
	<view>
		<view class="display-ce" v-show="!is_code">
			<view class="btn text-align-center fontSize-32" style="margin: 300rpx auto 0 auto;" v-show="!checked" @click="toast">授权手机号登录</view>
			<button class="btn" @getphonenumber="getPhoneNumber" open-type="getPhoneNumber" v-show="checked">授权手机号登录</button>
			<view class="text-align-center mar-top-80" style="color: #2DB295;" @click="changeiscode(true)">短信验证码登录</view>
		</view>
		
		<!-- 短信登录表单 -->
		<view class="login_view" v-show="is_code">
			<view class="ipt display-ce align-items">
				<input type="number" placeholder="请输入手机号" v-model="mobile" maxlength="11" />
			</view>
			<view class="ipt display-ce align-items mar-top-40">
				<input type="number" placeholder="请输入验证码" v-model="code" maxlength="6" />
				<view class="code_btn" @click="sendCode" :class="{disabled: countdown > 0}">
					{{ countdown > 0 ? countdown + 's' : '获取验证码' }}
				</view>
			</view>
			<view class="login_btn text-align-center fontSize-32 mar-top-60" @click="handleSmsLogin">登录</view>
			<view class="text-align-center mar-top-40" style="color: #2DB295;" @click="changeiscode(false)">返回微信登录</view>
		</view>
		
		<view class="display-ce align-items fontSize-26 mar-top-40">
			<label class="radio" @click="changerideo"><radio value="r1" :checked="checked" color="#2DB295" style="transform:scale(0.7)" /> 阅读并同意<text style="color: #2DB295;" @click.stop="openshow(1)">《用户协议》</text>与<text style="color: #2DB295;" @click.stop="openshow(2)">《平台协议》</text></label>
		</view>
		<tm-overlay v-model:show="showWin" contentAnimation>
			<view @click.stop="" class="bgfff radius-26 width-80 pad-lr-20 pad-tb-20" style="height: 700rpx;overflow-y: scroll;">
				<view class="" v-if="pop_type==1">
					<tm-html :content="user_protocol"></tm-html>
				</view>
				<view class="" v-if="pop_type==2">
					<tm-html :content="privacy_protocol"></tm-html>
				</view>
			</view>
		</tm-overlay>
	</view>
</template>

<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app';
import {wxMobile,wxAuth,getParams,sendSmsCode,smsLogin} from '@/utils/api'
import { ref } from 'vue';
onLoad((options)=>{
	if(options.pid){
		pid.value = options.pid
	}
	_protocol()
})
const pid=ref('')
const showWin = ref(false)
const is_code = ref(false)
const mobile = ref('')
const code = ref('')
const countdown = ref(0)
const getPhoneNumber =(e) =>{
	console.log(pid.value||uni.getStorageSync('pid'))
	uni.login({
		success(res) {
			wxAuth({code:res.code,parent_id:pid.value||uni.getStorageSync('pid')}).then(resx=>{
				if(resx.code==22){
					console.log(e.detail.code,resx.data.openid)
					wxMobile({mobile_code:e.detail.code,openid:resx.data.openid}).then(res=>{
						if(res.code==1){
							uni.setStorageSync('token',res.data.token)
							uni.setStorageSync('id',res.data.id)
							uni.switchTab({
								url:'/pages/index/index'
							})
						}else{
							uni.showToast({
								title:res.msg,
								icon:'none'
							})
						}
					})
				}else if(resx.code==1){
					uni.setStorageSync('token',resx.data.token)
					uni.setStorageSync('id',resx.data.id)
					uni.switchTab({
						url:'/pages/index/index'
					})
				}else{
					uni.showToast({
						title:resx.msg,
						icon:'none'
					})
				}
			})
		}
	})
}
const toast = () =>{
	if(!checked.value){
			uni.showToast({
				title:'请阅读并同意相关协议',
				icon:'none'
			})
			return
		}
}
const user_protocol = ref()//用户协议
const privacy_protocol = ref()//平台协议
const _protocol =() =>{
	getParams({fields:['privacy_policy','platform_protocol']}).then(res=>{
		if(res.code==1){
			user_protocol.value = res.data.privacy_policy
			privacy_protocol.value = res.data.platform_protocol
		}
	})
}

const checked = ref(false)//是否同意协议
const changerideo =() =>{
	checked.value = !checked.value
}
const pop_type = ref()
const openshow =(type:number) =>{
	pop_type.value = type
	showWin.value = true
}

// 切换登录方式
const changeiscode = (show: boolean) => {
	is_code.value = show
	if (!show) {
		// 重置表单
		mobile.value = ''
		code.value = ''
		countdown.value = 0
	} else {
		// 切换到短信登录时，确保协议状态正确
		// 如果用户已经勾选了协议，保持勾选状态
		// 如果用户没有勾选，需要重新勾选
	}
}

// 发送短信验证码
const sendCode = () => {
	if (countdown.value > 0) return
	
	if (!mobile.value) {
		uni.showToast({
			title: '请输入手机号',
			icon: 'none'
		})
		return
	}
	
	if (!/^1[3-9]\d{9}$/.test(mobile.value)) {
		uni.showToast({
			title: '请输入正确的手机号',
			icon: 'none'
		})
		return
	}
	
	sendSmsCode({ mobile: mobile.value }).then(res => {
		if (res.code === 1) {
			uni.showToast({
				title: '验证码已发送',
				icon: 'success'
			})
			// 开发环境提示固定验证码
			// #ifdef H5
			// if (process.env.NODE_ENV === 'development') {
			// 	setTimeout(() => {
			// 		uni.showModal({
			// 			title: '开发环境提示',
			// 			content: '验证码：123456（开发环境固定验证码）',
			// 			showCancel: false
			// 		})
			// 	}, 1000)
			// }
			// #endif
			// 开始倒计时
			countdown.value = 60
			const timer = setInterval(() => {
				countdown.value--
				if (countdown.value <= 0) {
					clearInterval(timer)
				}
			}, 1000)
		} else {
			uni.showToast({
				title: res.msg || '发送失败',
				icon: 'none'
			})
		}
	}).catch(err => {
		uni.showToast({
			title: '发送失败',
			icon: 'none'
		})
	})
}

// 短信验证码登录
const handleSmsLogin = () => {
	// 检查协议勾选状态
	console.log('协议勾选状态:', checked.value)
	if (!checked.value) {
		uni.showToast({
			title: '请阅读并同意相关协议',
			icon: 'none'
		})
		return
	}
	
	if (!mobile.value) {
		uni.showToast({
			title: '请输入手机号',
			icon: 'none'
		})
		return
	}
	
	if (!code.value) {
		uni.showToast({
			title: '请输入验证码',
			icon: 'none'
		})
		return
	}
	
	if (!/^1[3-9]\d{9}$/.test(mobile.value)) {
		uni.showToast({
			title: '请输入正确的手机号',
			icon: 'none'
		})
		return
	}
	
	// 先获取微信用户信息
	uni.getUserProfile({
		desc: '用于完善用户资料',
		success: (userInfoRes) => {
			console.log('获取到微信用户信息:', userInfoRes)
			
			// 调用短信登录API，传递用户信息
			smsLogin({ 
				mobile: mobile.value, 
				code: code.value,
				parent_id: pid.value || uni.getStorageSync('pid') || '',
				nickname: userInfoRes.userInfo.nickName || '',
				avatar: userInfoRes.userInfo.avatarUrl || ''
			}).then(res => {
				if (res.code === 1) {
					uni.setStorageSync('token', res.data.token)
					uni.setStorageSync('id', res.data.id)
					uni.switchTab({
						url: '/pages/index/index'
					})
				} else {
					uni.showToast({
						title: res.msg || '登录失败',
						icon: 'none'
					})
				}
			}).catch(err => {
				uni.showToast({
					title: '登录失败',
					icon: 'none'
				})
			})
		},
		fail: (err) => {
			console.log('获取微信用户信息失败:', err)
			// 即使获取用户信息失败，也继续登录，但不传递用户信息
			smsLogin({ 
				mobile: mobile.value, 
				code: code.value,
				parent_id: pid.value || uni.getStorageSync('pid') || ''
			}).then(res => {
				if (res.code === 1) {
					uni.setStorageSync('token', res.data.token)
					uni.setStorageSync('id', res.data.id)
					uni.switchTab({
						url: '/pages/index/index'
					})
				} else {
					uni.showToast({
						title: res.msg || '登录失败',
						icon: 'none'
					})
				}
			}).catch(err => {
				uni.showToast({
					title: '登录失败',
					icon: 'none'
				})
			})
		}
	})
}
</script>

<style lang="scss">
.btn{
	width: 600rpx;
	height: 100rpx;
	background: linear-gradient(270deg, #bc8c1e 0%, #fdfdfd 100%);
	border-radius: 50rpx 50rpx 50rpx 50rpx;
	line-height: 100rpx;
	color: #fff;
	margin-top: 300rpx;
}
.body_view{
		margin-top: calc(var(--status-bar-height) + 196rpx);
	}
.login_view{
	box-shadow: 0rpx 6rpx 12rpx 0rpx rgba(45, 178, 149, 0.2);
	border-radius: 32rpx 32rpx 32rpx 32rpx;
	padding: 30rpx 50rpx 50rpx 50rpx;
	margin-top: 60rpx;
}
.login_btn{
	height: 80rpx;
	background: linear-gradient(270deg, #bc8c1e 0%, #fdfdfd 100%);
	border-radius: 50rpx 50rpx 50rpx 50rpx;
	line-height: 80rpx;
}
.ipt{
	border-bottom: 2rpx solid #F1F1F1;
}
.tel_img{
	width: 222rpx;
	height: 210rpx;
}
.tel_btn{
	height: 80rpx;
	background: linear-gradient(270deg, #bc8c1e 0%, #fdfdfd 100%);
	border-radius: 50rpx 50rpx 50rpx 50rpx;
	line-height: 80rpx;
	width: 600rpx;
	margin: 40rpx auto 0 auto;
}
.active_view{
	background: #F9F9F9;
	border-radius: 40rpx 40rpx 40rpx 40rpx;
	.xia_img{
		width: 28rpx;
		height: 28rpx;
	}
	.txt_scoll{
		overflow-x: scroll;
		width: 90%;
		display: block;
		white-space: nowrap;
	}
}
.quxiao{
	width: 240rpx;
	height: 80rpx;
	border-radius: 40rpx 40rpx 40rpx 40rpx;
	color: #4770AD;
	line-height: 80rpx;
	border: 2rpx solid #4770AD;
}
.qury{
	width: 240rpx;
	height: 80rpx;
	background: linear-gradient(270deg, #bc8c1e 0%, #fdfdfd 100%);
	border-radius: 40rpx 40rpx 40rpx 40rpx;
	line-height: 80rpx;
}
.col-2DB295{
	color: #2BBEA0;
}

.code_btn{
	background: linear-gradient(270deg, #bc8c1e 0%, #fdfdfd 100%);
	color: #fff;
	padding: 10rpx 20rpx;
	border-radius: 10rpx;
	font-size: 24rpx;
	white-space: nowrap;
	margin-left: 20rpx;
}

.code_btn.disabled{
	background: #ccc;
	color: #999;
}

.login_view{
	box-shadow: 0rpx 6rpx 12rpx 0rpx rgba(45, 178, 149, 0.2);
	border-radius: 32rpx 32rpx 32rpx 32rpx;
	padding: 30rpx 50rpx 50rpx 50rpx;
	margin-top: 60rpx;
}

.ipt{
	border-bottom: 2rpx solid #F1F1F1;
	padding: 20rpx 0;
}

.ipt input{
	flex: 1;
	font-size: 28rpx;
}
</style>
